package com.ccl.iot.publics;

public class ConvertFunctions {
	/*
	 * Convert signed byte to unsigned short
	 */
	public static final short Byte2Short(byte aByte){
		if (aByte < 0){
			return (short)(256 + aByte);
		}else{
			return aByte;
		}
	}

	/*
	 * Convert signed int to unsigned long
	 */
	public static final long Int2Long(int aIntValue){
		long tmpLong = aIntValue;
		if (aIntValue < 0){
			tmpLong = -(tmpLong);
			tmpLong = (long)((long)0x80000000 + tmpLong);
		}
		return tmpLong;
	}
	
	/*
	 * Get unsigned short by high bit and low bit
	 */
	public static final int MixUShort(byte aLowBit, byte aHighBit){
		return (int) (((int)aLowBit & 0xFF)) | 
						(((int)aHighBit & 0xFF) << 8);
	}
	
	/*
	 * Byte array to integer
	 */
	public static final int ByteArray2UShort(byte aArr[], int aStartPos){
		if (aArr.length - aStartPos > 1){
			return (int) ((int)aArr[aStartPos + 0] & 0xFF) | 
					(((int)aArr[aStartPos + 1] & 0xFF) << 8);
		}
		return 0;
	}
	
	/*
	 * Byte array to integer
	 */
	public static final long ByteArray2UInt(byte aArr[], int aStartPos){
		if (aArr.length - aStartPos > 3){
			return (long) ((long)aArr[aStartPos + 0] & 0xFF) | 
					(((long)aArr[aStartPos + 1] & 0xFF) << 8) | 
					(((long)aArr[aStartPos + 2] & 0xFF)) << 16 | 
					(((long)aArr[aStartPos + 3] & 0xFF) << 24);
		}
		return 0;
	}
	
	/*
	 * Byte array to long
	 */
	public static final long ByteArray2Long(byte aArr[], int aStartPos){
		if (aArr.length - aStartPos > 7){
			return (long) ((long)aArr[aStartPos + 0] & 0xFF) | 
					(((long)aArr[aStartPos + 1] & 0xFF) << 8) | 
					(((long)aArr[aStartPos + 2] & 0xFF)) << 16 | 
					(((long)aArr[aStartPos + 3] & 0xFF) << 24) |
					(((long)aArr[aStartPos + 3] & 0xFF) << 32) |
					(((long)aArr[aStartPos + 3] & 0xFF) << 40) |
					(((long)aArr[aStartPos + 3] & 0xFF) << 48) |
					(((long)aArr[aStartPos + 3] & 0xFF) << 54);
		}
		
		return 0;
	}
	
	public static final byte[] UInt2ByteArray(long aUInt){
		byte tBytes[] = new byte[4];
		
		tBytes[0] = (byte) (aUInt & 0xFF);
		tBytes[1] = (byte) ((aUInt >> 8) & 0xFF);
		tBytes[2] = (byte) ((aUInt >> 16) & 0xFF);
		tBytes[3] = (byte) ((aUInt >> 24) & 0xFF);
		
		return tBytes;
	}
	
	/*
	 * String convert to integer
	 */
	public static final int String2Int(String aString, int aMinVal){
		int tVal = 0;
		try{
			tVal = Integer.parseInt(aString);
			
			if (tVal < aMinVal){
				tVal = aMinVal;
			}
		}catch (Exception e){
			tVal = aMinVal;
		}
		return tVal;
	}
}
